<template>
  <div :class="['swipe', className]">
    <van-swipe ref="swipe" style="height: 100%;" :initial-swipe="initialSwipe" @change="changeHandle">
      <van-swipe-item v-for="(l,i) in list" :key="i">
        <ImageVideo :src="l.src" :poster="l.poster" :fit="fit" :is-image="l.type === 'image'" @video-click="videoClickHandle" />
      </van-swipe-item>
      <template #indicator>
        <div v-show="!isVideo" class="indicator"><span class="curent-index">{{ index + 1 }}</span>/{{ list.length }}</div>
      </template>
    </van-swipe>
  </div>
</template>
<script>
import ImageVideo from '@/components/ImageVideo'
export default {
  name: 'Swipe',
  components: {
    ImageVideo
  },
  props: {
    list: {
      type: [Array],
      default: () => []
    },
    className: {
      type: String,
      default: ''
    },
    fit: {
      type: String,
      default: 'fill'
    },
    value: {
      type: Number,
      default: 0
    },
    initialSwipe: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      index: 0,
      videoIndex: null
    }
  },
  computed: {
    isVideo() {
      return this.videoIndex === this.index
    }
  },
  watch: {
    value: {
      handler(v) {
        this.index = v
      },
      immediate: true
    },
    index() {
      this.stopPlay(this.$children)
    },
    list: {
      handler(l) {
        for (let i = 0; i < l.length; i++) {
          if (l[i].type === 'video') {
            this.videoIndex = i
            break
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    changeHandle(v) {
      this.index = 0
      this.$emit('input', v)
    },
    videoClickHandle() {
      this.$emit('video-click')
    },
    // 暂停播放
    stopPlay(children) {
      for (const p of children) {
        if (p.$options.name === 'Player' && p.player && p.player.hasStart) {
          p.player.pause && p.player.pause()
        }
        if (p.$children) {
          this.stopPlay(p.$children)
        }
      }
    },
    swipeTo(index) {
      this.$refs.swipe.swipeTo(index)
    }
  }
}
</script>
<style lang="less" scoped>
.swipe{
  width: 375px;
  height: 375px;
  .indicator{
    position: absolute;
    right: 20px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    color: #fff;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    .curent-index{
      font-size: 18px;
    }
  }
}
</style>
<style lang="less">
  .xgplayer-poster{
    background-size: 100% 100% !important;
    background-position: center !important;
  }
</style>
